<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-11-10
 * Time: 13:31
 */

namespace app\api\controller;
use app\common\controller\ApiController;
use think\Db;

class Labels extends ApiController
{
    // 获取标签列表
    public function getList() {
        $param = $this->request->param();
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        $where[] = ['is_deleted','=',0];
        if(!empty($param['name'])) $where[] = ['name','like','%'.$param['name'].'%'];
        if(!empty($param['type_name']) && $param['type_name'] != 0) $where[] = ['type_name','=',$param['type_name']];
        $list = Db::name('wy_labels')->where($where)->page($param['pageNo'],$param['pageSize'])->order('id desc')->select();
        foreach ($list as $key=>$value) $list[$key]['type_name_text'] = $this->getTypeNameText($value['type_name']);
        $count = Db::name('wy_labels')->where($where)->count();
        return __success('ok',['data'=>$list,'pageSize'=>$param['pageSize'],'pageNo'=>$param['pageNo'],'totalCount'=>$count,'totalPage'=>ceil($count / $param['pageSize'])]);
    }

    // 添加or编辑标签
    public function operation() {
        $param = $this->request->param();
        if(empty($param['name'])) return __error('标签名称不可为空');
        if(empty($param['type_name'])) return __error('标签分类不可为空');
        // 查询标签信息->防止标签重复
        $labelsMap[] = ['name','=',$param['name']];
        $labelsMap[] = ['type_name','=',$param['type_name']];
        $labelsMap[] = ['is_deleted','=',0];
        if(!empty($param['id'])) $labelsMap[] = ['id','<>',$param['id']];
        $labelsInfo = Db::name('wy_labels')->where($labelsMap)->find();
        if(!empty($labelsInfo)) return __error('标签重复');
        // 添加标签
        if(empty($param['id'])){
            $param['pms_ar_id'] = $this->userinfo['pms_ar_id'];
            $addRes = Db::name('wy_labels')->strict(false)->insert($param,true,true);
            return empty($addRes) ? __error('添加失败') : __success('添加成功');
        }else{
            // 编辑标签
            unset($param['token']);
            $upRes = Db::name('wy_labels')->update($param);
            return $upRes !== false ? __success('修改成功') : __error('修改失败');
        }
    }

    // 删除标签
    public function del() {
        $id = $this->request->param('id');
        $labelInfo = Db::name('wy_labels')->where('id',$id)->find();
        $delRes = false;
        // if($labelInfo['type_name'] == 4){
            $findInfo = Db::name('wy_labels_middle')->where(['labels_id'=>$id])->column('id');
            if(!empty($findInfo)) return __error('当前标签有绑定数据,不可删除');
            else $delRes = Db::name('wy_labels')->where('id',$id)->delete();

        // }
        return empty($delRes) ? __error('删除失败') : __success('删除成功');
    }

    // 获取已绑定数据
    public function getBindData() {
        $id = $this->request->param('id');
        // 标签信息
        $labelsInfo = Db::name('wy_labels')->where('id',$id)->find();
        // 小区
        $communityList = Db::name('wy_bd_info')->where(['is_deleted'=>0,'pms_ar_id'=>$this->userinfo['pms_ar_id']])->field('id value,name label')->select();
        $communityIds = array();
        foreach ($communityList as $key=>$value) array_push($communityIds,$value['value']);
        $allData = array();
        // 房屋
        if($labelsInfo['type_name'] == 1){
            // 楼宇
            $buildingList = Db::name('wy_building')->where('bd_info_id','in',$communityIds)->where(['is_deleted'=>0])->field('id value,name label,bd_info_id,status')->select();
            $buildingIds = array();
            foreach ($buildingList as $key=>$value) array_push($buildingIds,$value['value']);
            // 单元
            $unitList = Db::name('wy_unit')->where('building_id','in',$buildingIds)->where(['is_deleted'=>0])->field('id value,name label,building_id')->select();
            $unitIds = array();
            foreach ($unitList as $key=>$value) array_push($unitIds,$value['value']);
            // 房屋
            $housesList = Db::name('wy_houses')->where('unit_id','in',$unitIds)->where(['is_deleted'=>0])->field('id value,name label,unit_id')->select();
            foreach ($communityList as $ck=>$cv){
                $cv['children'] = array();
                $cv['key'] = 'xq_' . $cv['value'];
                $cv['title'] = $cv['label'];
                foreach ($buildingList as $bk=>$bv){
                    switch($bv['status']){
                        case 0:
                            $bv['label']=$bv['label'].'(禁用)';
                            break;
                        case 2:
                            $bv['label']=$bv['label'].'(拆除)';
                            break;
                        case 3:
                            $bv['label']=$bv['label'].'(出售)';
                            break;
                        case 4:
                            $bv['label']=$bv['label'].'(其它)';
                            break;
                    }
                    $bv['children'] = array();
                    $bv['key'] = 'ly_' . $bv['value'];
                    $bv['title'] = $bv['label'];
                    if($bv['bd_info_id'] === $cv['value']) {
                        unset($bv['bd_info_id']);
                        foreach ($unitList as $uk=>$uv){
                            $uv['children'] = array();
                            $uv['key'] = 'dy_' . $uv['value'];
                            $uv['title'] = $uv['label'];
                            if($uv['building_id'] === $bv['value']) {
                                unset($uv['building_id']);
                                foreach ($housesList as $hk=>$hv){
                                    $hv['key'] = 'fw_' . $hv['value'];
                                    $hv['title'] = $hv['label'];
                                    if($hv['unit_id'] === $uv['value']){
                                        unset($hv['unit_id']);
                                        array_push($uv['children'],$hv);
                                    }
                                }
                                if(!empty($uv['children'])) array_push($bv['children'],$uv);
                            }
                        }
                        if(!empty($bv['children'])) array_push($cv['children'],$bv);
                    }
                }
                if(!empty($cv['children'])) array_push($allData,$cv);
            }
            $bindList = Db::name('wy_houses')->where(['labels'=>$id,'is_deleted'=>0])->column('id');
            foreach ($bindList as $key=>$value) $bindList[$key] = 'fw_' . $value;
        }
        // 车位
        if($labelsInfo['type_name'] == 2){
            $carAreaList = Db::name('wy_car_area')->where('bd_info_id','in',$communityIds)->where(['is_deleted'=>0])->field('id value,name label,bd_info_id')->select();
            foreach ($communityList as $ck=>$cv){
                $cv['children'] = array();
                $cv['key'] = 'xq_' . $cv['value'];
                $cv['title'] = $cv['label'];
                foreach ($carAreaList as $bk=>$bv){
                    $bv['key'] = 'cw_' . $bv['value'];
                    $bv['title'] = $bv['label'];
                    if($bv['bd_info_id'] === $cv['value']) {
                        unset($bv['bd_info_id']);
                        array_push($cv['children'],$bv);
                    }
                }
                if(!empty($cv['children'])) array_push($allData,$cv);
            }
            $bindList = Db::name('wy_car_area')->where(['labels_id'=>$id,'is_deleted'=>0])->column('id');
            foreach ($bindList as $key=>$value) $bindList[$key] = 'cw_' . $value;
        }
        // 车辆
        if($labelsInfo['type_name'] == 3){
            $carList = Db::name('wy_car')->where('bd_info_id','in',$communityIds)->where(['is_deleted'=>0])->field('id value,name label,bd_info_id')->select();
            foreach ($communityList as $ck=>$cv){
                $cv['children'] = array();
                $cv['key'] = 'xq_' . $cv['value'];
                $cv['title'] = $cv['label'];
                foreach ($carList as $bk=>$bv){
                    $bv['key'] = 'cl_' . $bv['value'];
                    $bv['title'] = $bv['label'];
                    if($bv['bd_info_id'] === $cv['value']) {
                        unset($bv['bd_info_id']);
                        array_push($cv['children'],$bv);
                    }
                }
                if(!empty($cv['children'])) array_push($allData,$cv);
            }
            $bindList = Db::name('wy_car')->where(['labels_id'=>$id,'is_deleted'=>0])->column('id');
            foreach ($bindList as $key=>$value) $bindList[$key] = 'cl_' . $value;
        }
        return __success('ok',['list'=>$allData,'bind'=>$bindList]);
    }

    // 绑定车位、车辆、房屋标签
    public function horpBindLabels() {
        $id = $this->request->param('id');
        if(empty($id)) return __error('参数错误');
        $has = $this->request->param('has'); // 已绑定数据 [1,3]
        $bindIds = $this->request->param('ids'); // 选中数据 [3,4,5,56,7]
        // 标签信息
        $labelsInfo = Db::name('wy_labels')->where('id',$id)->find();
        $upData = array();
        // 房屋
        if($labelsInfo['type_name'] == 1){
            foreach ($bindIds as $k=>$v) array_push($upData,['id'=>$v,'labels'=>$labelsInfo['id']]);
            foreach ($has as $key=>$value) if(!in_array($value,$bindIds)) array_push($upData,['id'=>$value,'labels'=>0]);
            $upRes = model('WyHouses')->saveAll($upData);
        }
        // 车位
        if($labelsInfo['type_name'] == 2){
            foreach ($bindIds as $k=>$v) array_push($upData,['id'=>(int)$v,'labels_id'=>$labelsInfo['id']]);
            foreach ($has as $key=>$value) if(!in_array($value,$bindIds)) array_push($upData,['id'=>$value,'labels_id'=>0]);
            $upRes = model('WyCarArea')->saveAll($upData);
        }
        // 车辆
        if($labelsInfo['type_name'] == 3){
            foreach ($bindIds as $k=>$v) array_push($upData,['id'=>(int)$v,'labels_id'=>$labelsInfo['id']]);
            foreach ($has as $key=>$value) if(!in_array($value,$bindIds)) array_push($upData,['id'=>$value,'labels_id'=>0]);
            $upRes = model('WyCar')->saveAll($upData);
        }
        return $upRes !== false ? __success('绑定成功') : __error('绑定失败');
    }

    // 获取绑定住户列表
    public function getBindList() {
        $param = $this->request->param();
        $where[] = ['m.labels_id','=',$param['id']];
        if(!empty($param['search'])) $where[] = ['u.name|u.phone','like','%'.$param['search'].'%'];
        $labelsInfo = Db::name('wy_labels')->where('id',$param['id'])->find();
        $list = Db::name('wy_labels_middle')->alias('m')
            ->join('wy_house_user u','m.house_user_id = u.id')
            ->join('wy_bd_info bd','u.bd_info_id = bd.id')
            ->field('m.id,u.name,u.phone,bd.name bd_name')
            ->where($where)->page($param['pageNo'],$param['pageSize'])
            ->order('m.id desc')->select();
        $count = Db::name('wy_labels_middle')->alias('m')
            ->join('wy_house_user u','m.house_user_id = u.id')
            ->join('wy_bd_info bd','u.bd_info_id = bd.id')->where($where)->count();
        return __success('ok',['data'=>$list,'pageSize'=>$param['pageSize'],'pageNo'=>$param['pageNo'],'totalCount'=>$count,'totalPage'=>ceil($count / $param['pageSize']),'labels_name'=>$labelsInfo['name']]);
    }

    // 解绑住户
    public function removeBindUser() {
        $ids = $this->request->param('ids');
        if(empty($ids)) return __error('参数错误');
        $delRes = Db::name('wy_labels_middle')->where('id','in',$ids)->delete();
        return empty($delRes) ? __error('解绑失败') : __success('解绑成功');
    }

    // 获取绑定用户列表
    public function getBindUserList(){
        $id = $this->request->param('id');
        $text = $this->request->param('text');
        $bd_info_id = $this->request->param('bd_info_id');
        if(empty($text)) return __success('ok',[]);
        if(mb_strlen($text) < 2) return __success('ok',[]);
        
        $where='status in (1,4)';
        if ($text) {
            $hids = Db::name('wy_houses')->where('name','like','%'.$text.'%')->column('id');
            $likes=implode(',',$hids);
            if ($hids) {
                $where .= ' and (phone like \''.$text.'%\' or name like \''.$text.'%\' or houses_id in ('.$likes.'))';
            } else {
                $where .= ' and (phone like \''.$text.'%\' or name like \''.$text.'%\' )';
            }
        }
        $list = Db::name('wy_house_user')->where($where)->field('id value,bd_info_id,building_id,houses_id,name,phone,status')->limit(20)->order('houses_id desc')->select();
        foreach ($list as $key=>$value){
            $bd_info_text = Db::name('wy_bd_info')->where('id',$value['bd_info_id'])->value('name');
            // $building_text = Db::name('wy_building')->where('id',$value['building_id'])->value('name');
            $houses_text = Db::name('wy_houses')->where('id',$value['houses_id'])->value('name');
            if ($value['status'] == 4) {
                $list[$key]['label'] =  '非住户'.'-'.$value['name'].'-'.$value['phone'];
            } else {
                if($bd_info_text && $houses_text){
                    $list[$key]['label'] =  $bd_info_text.'-'.$houses_text.'-'.$value['name'].'-'.$value['phone'];
                }else{
                    $list[$key]['label'] =  '非住户'.'-'.$value['name'].'-'.$value['phone'];
                }
                
            }
        }
        return __success('ok',$list);
    }

    // 绑定用户
    public function bindUser() {
        $labels_id = $this->request->param('id');
        $house_user_id = $this->request->param('house_user_id');
        if(empty($labels_id)) return __error('参数错误');
        if(empty($house_user_id)) return __error('住户不可为空');
        foreach ($house_user_id as $key=>$value){
            $findInfo = Db::name('wy_labels_middle')->where(['labels_id'=>$labels_id,'house_user_id'=>$value])->find();
            if(empty($findInfo)){
                $res = Db::name('wy_labels_middle')->insert(['labels_id'=>$labels_id,'house_user_id'=>$value]);
            }else $res = true;
        }
        return empty($res) ? __error('绑定失败') : __success('绑定成功');
    }

    // 根据分类id获取对应文字
    function getTypeNameText($type) {
        return [1=>'房屋标签',2=>'车位标签',3=>'车辆标签',4=>'住户标签'][$type];
    }
}